package gui;

import entity.Student;
import service.StudentManager;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

/**
 * 学生信息管理面板
 */
public class StudentPanel extends JPanel {
    private final StudentManager studentManager;
    
    // UI组件
    private JTable studentTable;
    private DefaultTableModel tableModel;
    private JTextField idField, nameField, ageField, majorField, enrollDateField;
    private JButton addButton, updateButton, deleteButton, clearButton;
    private JTextField searchField;
    private JButton searchButton, exportButton, importButton;
    
    /**
     * 构造函数
     */
    public StudentPanel(StudentManager studentManager) {
        this.studentManager = studentManager;
        initUI();
    }
    
    /**
     * 初始化UI
     */
    private void initUI() {
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 创建顶部搜索面板
        JPanel searchPanel = createSearchPanel();
        
        // 创建表格
        createTable();
        
        // 创建表单
        JPanel formPanel = createFormPanel();
        
        // 创建按钮面板
        JPanel buttonPanel = createButtonPanel();
        
        // 将表单和按钮面板放在一起
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.add(formPanel, BorderLayout.CENTER);
        inputPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // 添加组件到面板
        add(searchPanel, BorderLayout.NORTH);
        add(new JScrollPane(studentTable), BorderLayout.CENTER);
        add(inputPanel, BorderLayout.SOUTH);
        
        // 初始化表格数据
        refreshData();
    }
    
    /**
     * 创建搜索面板
     */
    private JPanel createSearchPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        panel.setBorder(BorderFactory.createTitledBorder("搜索学生"));
        
        searchField = new JTextField(20);
        searchButton = ThemeManager.createButton("搜索");
        exportButton = ThemeManager.createSuccessButton("导出");
        importButton = ThemeManager.createButton("导入");
        
        searchButton.addActionListener(e -> searchStudents());
        exportButton.addActionListener(e -> exportStudents());
        importButton.addActionListener(e -> importStudents());
        
        panel.add(new JLabel("搜索(学号/姓名):"));
        panel.add(searchField);
        panel.add(searchButton);
        panel.add(Box.createHorizontalStrut(20));
        panel.add(exportButton);
        panel.add(importButton);
        
        return panel;
    }
    
    /**
     * 创建表格
     */
    private void createTable() {
        // 表格列名
        String[] columnNames = {"学号", "姓名", "年龄", "专业", "入学日期"};
        
        // 创建表格模型
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 设置表格不可编辑
            }
        };
        
        // 创建表格
        studentTable = new JTable(tableModel);
        studentTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        studentTable.getTableHeader().setReorderingAllowed(false);
        
        // 添加表格选择监听器
        studentTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = studentTable.getSelectedRow();
                if (selectedRow != -1) {
                    // 获取选中行的数据
                    String id = (String) tableModel.getValueAt(selectedRow, 0);
                    String name = (String) tableModel.getValueAt(selectedRow, 1);
                    int age = (int) tableModel.getValueAt(selectedRow, 2);
                    String major = (String) tableModel.getValueAt(selectedRow, 3);
                    String enrollDate = (String) tableModel.getValueAt(selectedRow, 4);
                    
                    // 填充表单
                    idField.setText(id);
                    idField.setEditable(false); // 学号不可编辑
                    nameField.setText(name);
                    ageField.setText(String.valueOf(age));
                    majorField.setText(major);
                    enrollDateField.setText(enrollDate);
                }
            }
        });
    }
    
    /**
     * 创建表单面板
     */
    private JPanel createFormPanel() {
        JPanel panel = new JPanel(new GridLayout(5, 2, 5, 5));
        panel.setBorder(BorderFactory.createTitledBorder("学生信息"));
        
        // 创建表单字段
        idField = new JTextField(20);
        nameField = new JTextField(20);
        ageField = new JTextField(20);
        majorField = new JTextField(20);
        enrollDateField = new JTextField(20);
        
        // 添加组件到面板
        panel.add(new JLabel("学号:"));
        panel.add(idField);
        panel.add(new JLabel("姓名:"));
        panel.add(nameField);
        panel.add(new JLabel("年龄:"));
        panel.add(ageField);
        panel.add(new JLabel("专业:"));
        panel.add(majorField);
        panel.add(new JLabel("入学日期 (yyyy-MM-dd):"));
        panel.add(enrollDateField);
        
        return panel;
    }
    
    /**
     * 创建按钮面板
     */
    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        
        // 创建按钮
        addButton = ThemeManager.createSuccessButton("添加");
        updateButton = ThemeManager.createButton("修改");
        deleteButton = ThemeManager.createDangerButton("删除");
        clearButton = ThemeManager.createButton("清空");
        
        // 添加按钮事件
        addButton.addActionListener(e -> addStudent());
        updateButton.addActionListener(e -> updateStudent());
        deleteButton.addActionListener(e -> deleteStudent());
        clearButton.addActionListener(e -> clearForm());
        
        // 添加按钮到面板
        panel.add(addButton);
        panel.add(updateButton);
        panel.add(deleteButton);
        panel.add(clearButton);
        
        return panel;
    }
    
    /**
     * 添加学生
     */
    private void addStudent() {
        // 获取表单数据
        String id = idField.getText().trim();
        String name = nameField.getText().trim();
        String ageText = ageField.getText().trim();
        String major = majorField.getText().trim();
        String enrollDateText = enrollDateField.getText().trim();
        
        // 验证数据
        if (id.isEmpty() || name.isEmpty() || ageText.isEmpty() || major.isEmpty() || enrollDateText.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写所有字段！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        try {
            int age = Integer.parseInt(ageText);
            if (age <= 0 || age > 100) {
                JOptionPane.showMessageDialog(this, "年龄必须在1-100之间！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            LocalDate enrollDate;
            try {
                enrollDate = LocalDate.parse(enrollDateText, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            } catch (DateTimeParseException e) {
                JOptionPane.showMessageDialog(this, "日期格式不正确，请使用yyyy-MM-dd格式！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 创建学生对象
            Student student = new Student(id, name, age, major, enrollDate);
            
            // 添加学生
            if (studentManager.getStudentMap().containsKey(id)) {
                JOptionPane.showMessageDialog(this, "学号已存在！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            studentManager.addStudent(student);
            
            // 刷新表格
            refreshData();
            
            // 清空表单
            clearForm();
            
            JOptionPane.showMessageDialog(this, "学生添加成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "年龄必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 更新学生
     */
    private void updateStudent() {
        // 获取表单数据
        String id = idField.getText().trim();
        String name = nameField.getText().trim();
        String ageText = ageField.getText().trim();
        String major = majorField.getText().trim();
        String enrollDateText = enrollDateField.getText().trim();
        
        // 验证数据
        if (id.isEmpty() || name.isEmpty() || ageText.isEmpty() || major.isEmpty() || enrollDateText.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写所有字段！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        try {
            int age = Integer.parseInt(ageText);
            if (age <= 0 || age > 100) {
                JOptionPane.showMessageDialog(this, "年龄必须在1-100之间！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            LocalDate enrollDate;
            try {
                enrollDate = LocalDate.parse(enrollDateText, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            } catch (DateTimeParseException e) {
                JOptionPane.showMessageDialog(this, "日期格式不正确，请使用yyyy-MM-dd格式！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 创建学生对象
            Student student = new Student(id, name, age, major, enrollDate);
            
            // 更新学生
            studentManager.updateStudent(student);
            
            // 刷新表格
            refreshData();
            
            // 清空表单
            clearForm();
            
            JOptionPane.showMessageDialog(this, "学生信息更新成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "年龄必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 删除学生
     */
    private void deleteStudent() {
        int selectedRow = studentTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的学生！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        String id = (String) tableModel.getValueAt(selectedRow, 0);
        
        int option = JOptionPane.showConfirmDialog(
                this,
                "确定要删除学号为 " + id + " 的学生吗？",
                "删除确认",
                JOptionPane.YES_NO_OPTION);
        
        if (option == JOptionPane.YES_OPTION) {
            studentManager.deleteStudent(id);
            refreshData();
            clearForm();
        }
    }
    
    /**
     * 清空表单
     */
    private void clearForm() {
        idField.setText("");
        idField.setEditable(true);
        nameField.setText("");
        ageField.setText("");
        majorField.setText("");
        enrollDateField.setText("");
        studentTable.clearSelection();
    }
    
    /**
     * 刷新表格数据
     */
    public void refreshData() {
        // 清空表格
        tableModel.setRowCount(0);
        
        // 添加数据到表格
        for (Student student : studentManager.getStudentMap().values()) {
            Object[] rowData = {
                    student.getStudentID(),
                    student.getName(),
                    student.getAge(),
                    student.getMajor(),
                    student.getEnrollDate().toString()
            };
            tableModel.addRow(rowData);
        }
    }
    
    /**
     * 搜索学生
     */
    private void searchStudents() {
        String keyword = searchField.getText().trim();
        if (keyword.isEmpty()) {
            refreshData(); // 如果搜索关键字为空，显示所有学生
            return;
        }
        
        // 清空表格
        tableModel.setRowCount(0);
        
        // 搜索匹配的学生
        for (Student student : studentManager.getStudentMap().values()) {
            if (student.getStudentID().contains(keyword) || student.getName().contains(keyword)) {
                Object[] rowData = {
                        student.getStudentID(),
                        student.getName(),
                        student.getAge(),
                        student.getMajor(),
                        student.getEnrollDate().toString()
                };
                tableModel.addRow(rowData);
            }
        }
    }
    
    /**
     * 导出学生数据
     */
    private void exportStudents() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("导出学生数据");
        fileChooser.setSelectedFile(new java.io.File("students_export.csv"));
        
        int userSelection = fileChooser.showSaveDialog(this);
        
        if (userSelection == JFileChooser.APPROVE_OPTION) {
            java.io.File fileToSave = fileChooser.getSelectedFile();
            try (java.io.PrintWriter writer = new java.io.PrintWriter(fileToSave)) {
                // 写入表头
                writer.println("学号,姓名,年龄,专业,入学日期");
                
                // 写入数据
                for (Student student : studentManager.getStudentMap().values()) {
                    writer.printf("%s,%s,%d,%s,%s%n",
                            student.getStudentID(),
                            student.getName(),
                            student.getAge(),
                            student.getMajor(),
                            student.getEnrollDate().toString());
                }
                
                JOptionPane.showMessageDialog(this, "数据导出成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "导出失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    /**
     * 导入学生数据
     */
    private void importStudents() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("导入学生数据");
        
        int userSelection = fileChooser.showOpenDialog(this);
        
        if (userSelection == JFileChooser.APPROVE_OPTION) {
            java.io.File fileToOpen = fileChooser.getSelectedFile();
            try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader(fileToOpen))) {
                String line;
                boolean isFirstLine = true;
                int importedCount = 0;
                
                while ((line = reader.readLine()) != null) {
                    if (isFirstLine) {
                        isFirstLine = false;
                        continue; // 跳过表头
                    }
                    
                    String[] parts = line.split(",");
                    if (parts.length == 5) {
                        String id = parts[0].trim();
                        String name = parts[1].trim();
                        int age = Integer.parseInt(parts[2].trim());
                        String major = parts[3].trim();
                        LocalDate enrollDate = LocalDate.parse(parts[4].trim());
                        
                        // 创建学生对象并添加
                        Student student = new Student(id, name, age, major, enrollDate);
                        if (!studentManager.getStudentMap().containsKey(id)) {
                            studentManager.addStudent(student);
                            importedCount++;
                        }
                    }
                }
                
                refreshData();
                JOptionPane.showMessageDialog(this, "成功导入 " + importedCount + " 条学生记录！", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "导入失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}